//
//  XMPPHelper.m
//  XMPPHelper
//
//  Created by 蔡成汉 on 15/5/7.
//  Copyright (c) 2015年 JW. All rights reserved.
//

#import "XMPPHelper.h"
#import "XMPPFramework.h"

/**
 *  XMPP动作类型
 */
typedef NS_ENUM(NSInteger, XMPPActionType){
    /**
     *  连接
     */
    Connect = 0,
    /**
     *  断开连接
     */
    DisConnetc = 1,
    /**
     *  注册新用户
     */
    Register = 2,
    /**
     *  请求添加好友
     */
    AddFriend = 3,
    
    /**
     *  接受添加好友
     */
    AcceptAddFriend = 4,
    /**
     *  删除好友
     */
    DeleteFriend = 5,
    /**
     *  创建聊天室
     */
    CreatChatRoom = 6,
    /**
     *  删除聊天室
     */
    DeleteChatRoom = 7,
    /**
     *  加入聊天室
     */
    JoinChatRoom = 8,
    /**
     *  离开聊天室
     */
    LeveChatRoom = 9
};

static XMPPHelper *myXMPPHelper;

@interface XMPPHelper ()<XMPPStreamDelegate,XMPPReconnectDelegate,XMPPRosterDelegate,XMPPRoomDelegate>
{
    /**
     *  密码
     */
    NSString *password;
    
    BOOL customCertEvaluation;
    
    /**
     *  XMPP是否连接 -- 默认为NO
     */
    BOOL isXmppConnected;
    
    /**
     *  是否为XMPP注册新用户
     */
    BOOL registerXMPPUser;
}

/**
 *  XMPP消息流
 */
@property (nonatomic , strong) XMPPStream *xmppStream;

/**
 *  XMPP重连类 -- 用于断线重连
 */
@property (nonatomic , strong) XMPPReconnect *xmppReconnect;

/**
 *  花名册 -- XMPP好友列表
 */
@property (nonatomic , strong) XMPPRoster *xmppRoster;

/**
 *  好友列表在CoreData中的操作类
 */
@property (nonatomic , strong) XMPPRosterCoreDataStorage *xmppRosterStorage;

@property (nonatomic , strong) XMPPvCardCoreDataStorage *xmppvCardStorage;

@property (nonatomic , strong) XMPPvCardTempModule *xmppvCardTempModule;

@property (nonatomic , strong) XMPPvCardAvatarModule *xmppvCardAvatarModule;

@property (nonatomic , strong) XMPPCapabilities *xmppCapabilities;

@property (nonatomic , strong) XMPPCapabilitiesCoreDataStorage *xmppCapabilitiesStorage;

/**
 *  聊天室
 */
@property (nonatomic , strong) XMPPRoom *xmppRoom;

/**
 *  聊天室在CoreData中的操作
 */
@property (nonatomic , strong) XMPPRoomCoreDataStorage *xmppRoomStorage;

/**
 *  登陆结果
 */
@property (nonatomic , copy) void(^connectResult)(BOOL connect, NSError *error);

/**
 *  注册新用户的结果
 */
@property (nonatomic , copy) void(^registerResult)(BOOL registerRusult, NSError *error);

/**
 *  消息发送的结果
 */
@property (nonatomic , copy) void(^messageSendResult)(Message *message, MessageSendType sendType);

@end

@implementation XMPPHelper
@synthesize xmppStream;
@synthesize xmppReconnect;
@synthesize isXmppConnected;
@synthesize xmppRoster;
@synthesize xmppRosterStorage;
@synthesize xmppRoom;
@synthesize xmppRoomStorage;
@synthesize connectResult;
@synthesize registerResult;
@synthesize messageSendResult;


/**
 *  单例创建XMPPHelper
 *
 *  @return 实例化之后的XMPPHelper
 */
+(XMPPHelper *)myXMPPHelper
{
    @synchronized(self){
        if (myXMPPHelper == nil)
        {
            myXMPPHelper = [[XMPPHelper alloc]init];
        }
    }
    return myXMPPHelper;
}

-(id)init
{
    self = [super init];
    if (self)
    {
        [self setupStream];
    }
    return self;
}

/**
 *  初始化XMPPHelper
 */
-(void)setupStream
{
    xmppStream = [[XMPPStream alloc]init];
    
    //后台运行
    xmppStream.enableBackgroundingOnSocket = YES;
    
    //重连
    xmppReconnect = [[XMPPReconnect alloc]init];
    
    //花名册 -- 好友列表
    xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];
    xmppRoster = [[XMPPRoster alloc]initWithRosterStorage:xmppRosterStorage dispatchQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    xmppRoster.autoFetchRoster = YES;
    xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;
    
    // Activate xmpp modules
    [xmppReconnect  activate:xmppStream];
    [xmppRoster     activate:xmppStream];
    
    // Add ourself as a delegate to anything we may be interested in
    [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [xmppReconnect addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //设置服务器地址和端口号
    [xmppStream setHostName:XMPPServerAddress];
    [xmppStream setHostPort:XMPPServerPort];
    
    // You may need to alter these settings depending on the server you're connecting to
    customCertEvaluation = YES;
}

/**
 *  连接XMPP -- 没有带上用户名和密码，但是需要从沙盒中获取用户名和密码
 *
 *  @param connect 连接的结果 -- 连接成功、连接失败(错误信息)
 */
-(void)connect:(void(^)(BOOL connect, NSError *error))result
{
    registerXMPPUser = NO;
    
    [self connect];
}

/**
 *  连接XMPP -- 带用户名和密码的连接
 *
 *  @param userName 用户名
 *  @param psd      用户密码
 *  @param result   连接结果 -- 连接成功、连接失败（错误信息）
 */
-(void)connectWithuserName:(NSString *)userName psd:(NSString *)psd result:(void (^)(BOOL, NSError *))result
{
    connectResult = result;
    if (userName != nil && userName.length >0 && psd != nil && psd.length >0)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setValue:userName forKey:XMPPUserName];
        [defaults setValue:psd forKey:XMPPUserPassword];
        [defaults synchronize];
        registerXMPPUser = NO;
        [self connect];
    }
    else
    {
        if (connectResult)
        {
            NSError *tpError = [NSError errorWithDomain:@"用户名或密码错误" code:0 userInfo:nil];
            connectResult(NO,tpError);
        }
    }
}

/**
 *  XMPP注册新用户 -- 注册新用户只需用户名和密码即可 -- 一般新用户注册需由后台服务器处理，但客户端XMPP也支持单纯的XMPP新用户注册。
 *
 *  @param userName 用户名 -- XMPP服务器用户名
 *  @param psd      用户密码 -- XMPP服务器用户密码
 */
/**
 *  注册XMPP新用户 -- 注册新用户只需用户名和密码即可 -- 一般新用户注册需由后台服务器处理，但客户端XMPP也支持单纯的XMPP新用户注册。
 *
 *  @param userName 用户名 -- XMPP服务器用户名
 *  @param psd      用户密码 -- XMPP服务器用户密码
 *  @param result   注册XMPP新用户结果 -- 以block形式返回
 */
-(void)registerXMPPUser:(NSString *)userName psd:(NSString *)psd result:(void (^)(BOOL registerResult, NSError *error))result
{
    registerResult = result;
    if (userName != nil && userName.length >0 && psd != nil && psd.length >0)
    {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setValue:userName forKey:XMPPUserName];
        [defaults setValue:psd forKey:XMPPUserPassword];
        [defaults synchronize];
        
        registerXMPPUser = YES;
        
        [self connect];
    }
}

/**
 *  添加好友 --- 这个操作应由本地服务器完成，添加好友操作发送给本地服务器，本地服务器再连接openfier服务器进行添加好友操作，然后返回添加结果。
 *
 *  @param friendName XMPP用户名
 */
-(void)addFriend:(NSString *)friendName
{
    //jid 好友XMPPJID
    XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",friendName,XMPPServerName]];
    [xmppRoster addUser:jid withNickname:@"我们私奔吧"];
//    [xmppRoster subscribePresenceToUser:jid];
}

/**
 *  删除好友 -- 这个操作应由本地服务器完成，将删除好友操作发送给本地服务器，本地服务器再连接openfier服务器进行删除好友操作，然后返回删除结果。
 *
 *  @param friendName XMPP用户名
 */
-(void)deleteFriend:(NSString *)friendName
{
    XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",friendName,XMPPServerName]];
    [xmppRoster removeUser:jid];
}

#warning 测试
-(void)getFriends
{
    NSXMLElement *query = [NSXMLElement elementWithName:@"query" xmlns:@"jabber:iq:roster"];
    NSXMLElement *iq = [NSXMLElement elementWithName:@"iq"];
    XMPPJID *myJID = self.xmppStream.myJID;
    [iq addAttributeWithName:@"from" stringValue:myJID.description];
    [iq addAttributeWithName:@"to" stringValue:myJID.domain];
    [iq addAttributeWithName:@"id" stringValue:@"123456"];
    [iq addAttributeWithName:@"type" stringValue:@"get"];
    [iq addChild:query];
    [self.xmppStream sendElement:iq];
}

/**
 *  创建聊天室
 *
 *  @param roomName 聊天室XMPP名
 */
-(void)creatChatRoom:(NSString *)roomName
{
    XMPPJID *roomJID = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@conference.%@",roomName,XMPPServerName]];
    
    if (xmppRoomStorage == nil)
    {
        xmppRoomStorage = [[XMPPRoomCoreDataStorage alloc]init];
    }
    XMPPRoom *myXMPPRoom = [[XMPPRoom alloc] initWithRoomStorage:xmppRoomStorage jid:roomJID];
    xmppRoom = myXMPPRoom;
    [myXMPPRoom activate:xmppStream];
    [myXMPPRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [myXMPPRoom joinRoomUsingNickname:@"唐宁" history:nil];
}

/**
 *  删除聊天室
 *
 *  @param roomName 聊天室XMPP名
 */
-(void)deleteChatRoom:(NSString *)roomName
{
    
}

/**
 *  加入聊天室
 *
 *  @param roomName 聊天室XMPP名
 */
-(void)joinChatRoom:(NSString *)roomName
{
    [self creatChatRoom:roomName];
}

/**
 *  推出聊天室
 *
 *  @param roomName 聊天室XMPP名
 */
-(void)leaveChatRoom:(NSString *)roomName
{
    
}

/**
 *  发送消息
 *
 *  @param message Message -- Message里包含了发送对象以及消息类型等各种信息
 *  @param result  发送结果 -- 发送中、发送成功、发送失败
 */
-(void)sendMessage:(Message *)message result:(void(^)(Message *message, MessageSendType sendType))result;
{
    messageSendResult = result;
    if (messageSendResult)
    {
        messageSendResult(message,MessageIsSending);
    }
    [self doSendMessage:message];
    //需要根据消息类型进行综合处理 -- 如果是文本消息，则直接发送；如果是图片或者文件，则需要将图片或者文件上传到服务器，让服务器返回一个图片或者文件的url，然后发送这个url。
}

/**
 *  执行发送消息
 *
 *  @param message Message
 */
-(void)doSendMessage:(Message *)message
{
    //生成<body>文档
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:[message jsonMessage]];
    //生成XML消息文档
    NSXMLElement *mes = [NSXMLElement elementWithName:@"message"];
    //消息类型
    [mes addAttributeWithName:@"type" stringValue:@"chat"];
    
    //消息接收者
    [mes addAttributeWithName:@"to" stringValue:[NSString stringWithFormat:@"%@@%@",message.toId, XMPPServerName]];
    
    //消息发送者
    [mes addAttributeWithName:@"from" stringValue:[NSString stringWithFormat:@"%@@%@",message.fromId, XMPPServerName]];
    
    //组合body
    [mes addChild:body];
    
    //xmppStream发送消息
    [xmppStream sendElement:mes];
    if (messageSendResult)
    {
        messageSendResult(message,MessageSendSuccess);
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Connect/disconnect
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 *  连接XMPP服务器 -- 根据用户名和密码
 *
 *  @return YES表示连接成功，NO表示连接失败
 */
-(BOOL)connect
{
    if ([xmppStream isConnected])
    {
        if (connectResult)
        {
            connectResult(YES,nil);
        }
        return YES;
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *xmppUserName = [defaults objectForKey:XMPPUserName];
    NSString *xmppUserPsd = [defaults objectForKey:XMPPUserPassword];
    
    NSString *myJID = [NSString stringWithFormat:@"%@@%@",xmppUserName,XMPPServerName];
    NSString *myPassword = xmppUserPsd;
    
    if (myJID == nil || myPassword == nil)
    {
        return NO;
    }
    
    [xmppStream setMyJID:[XMPPJID jidWithString:myJID]];
    password = myPassword;
    
    NSError *error = nil;
    if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error])
    {
        return NO;
    }
    return YES;
}

/**
 *  关闭连接
 */
-(void)disconnect
{
    [self goOffline];
    [xmppStream disconnect];
}

/**
 *  上线 -- 发送一个上线的消息
 */
-(void)goOnline
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"available"];
    [[self xmppStream] sendElement:presence];
}

/**
 *  下线 -- 发送一个下线的消息
 */
-(void)goOffline
{
    XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];
    [[self xmppStream] sendElement:presence];
}

/**
 *  销毁XMPPStream -- 当程序将要被系统清理，需要调用该方法 -- appDelegate中调用
 */
-(void)teardownStream
{
    [xmppStream removeDelegate:self];
    [xmppReconnect         deactivate];
    [xmppStream disconnect];
    
    xmppStream = nil;
    xmppReconnect = nil;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPStream Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 *  在开始连接的时候会调用这个方法，但。。。只有当连接结束，下一个连接开始的时候才会再次调用这个方法。而下一次连接 --- 只有再上一次连接有了结果，下一次连接才生效，否则无论连接多少次，都是无效的，除非上一个连接结束。
 *
 *  @param sender XMPPStream
 */
-(void)xmppStreamWillConnect:(XMPPStream *)sender
{
    NSLog(@"开始连接");
}

/**
 *  socket连接成功
 *
 *  @param sender XMPPStream
 *  @param socket socket
 */
-(void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket
{
    NSLog(@"socket连接成功");
}

-(void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings
{
    NSString *expectedCertName = [xmppStream.myJID domain];
    if (expectedCertName)
    {
        settings[(NSString *) kCFStreamSSLPeerName] = expectedCertName;
    }
    
    if (customCertEvaluation)
    {
        settings[GCDAsyncSocketManuallyEvaluateTrust] = @(YES);
    }
}

-(void)xmppStream:(XMPPStream *)sender didReceiveTrust:(SecTrustRef)trust completionHandler:(void (^)(BOOL))completionHandler
{
    dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(bgQueue, ^{
        SecTrustResultType result = kSecTrustResultDeny;
        OSStatus status = SecTrustEvaluate(trust, &result);
        if (status == noErr && (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified))
        {
            completionHandler(YES);
        }
        else
        {
            completionHandler(NO);
        }
    });
}

-(void)xmppStreamDidSecure:(XMPPStream *)sender
{
    
}

/**
 *  XMPP连接成功 -- 建立连接
 *
 *  @param sender XMPPStream
 */
-(void)xmppStreamDidConnect:(XMPPStream *)sender
{
    isXmppConnected = YES;
    NSError *error = nil;
    if (registerXMPPUser == NO)
    {
        if (![xmppStream authenticateWithPassword:password error:&error])
        {
            NSLog(@"Error authenticating: %@", error);
        }
    }
    else
    {
        if (![xmppStream registerWithPassword:password error:&error])
        {
            NSLog(@"Error registering: %@", error);
        }
    }
}

/**
 *  XMPP连接失败 -- 断开连接
 *
 *  @param sender XMPPStream
 *  @param error  错误信息
 */
-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
{
    if (connectResult)
    {
        connectResult(NO,error);
    }
}


-(void)xmppStreamWasToldToDisconnect:(XMPPStream *)sender
{
    
}

/**
 *  XMPP用户验证通过
 *
 *  @param sender XMPPStream
 */
-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    [self goOnline];
    if (connectResult)
    {
        connectResult(YES,nil);
    }
}

/**
 *  XMPP用户验证失败
 *
 *  @param sender XMPPStream
 *  @param error  错误信息
 */
-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error
{
    [self goOnline];
    if (connectResult)
    {
        NSError *tpError = [NSError errorWithDomain:@"身份验证未通过" code:0 userInfo:nil];
        connectResult(NO,tpError);
    }
}

/**
 *  注册XMPP新用户成功
 *
 *  @param sender XMPPStream
 */
-(void)xmppStreamDidRegister:(XMPPStream *)sender
{
    if (registerResult)
    {
        registerResult(YES,nil);
    }
}

/**
 *  注册XMPP新用户失败
 *
 *  @param sender XMPPStream
 *  @param error  错误信息
 */
-(void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error
{
    if (registerResult)
    {
        NSError *tpError = [NSError errorWithDomain:[[error elementForName:@"error"] stringValue] code:0 userInfo:nil];
        registerResult(NO,tpError);
    }
}

/**
 *  是否收到IQ
 *
 *  @param sender XMPPStream
 *  @param iq     IQ
 *
 *  @return YES表示收到了，NO表示未收到
 */
-(BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq
{
    if ([@"result" isEqualToString:iq.type])
    {
        NSXMLElement *query = iq.childElement;
        if ([@"query" isEqualToString:query.name])
        {
            NSArray *items = [query children];
            for (NSXMLElement *item in items)
            {
                NSString *jid = [item attributeStringValueForName:@"jid"];
                XMPPJID *xmppJID = [XMPPJID jidWithString:jid];
                NSLog(@"%@",xmppJID.user);
            }
        }
    }
    return YES;
}

/**
 *  发送IQ
 *
 *  @param sender XMPPStream
 *  @param iq     IQ
 */
-(void)xmppStream:(XMPPStream *)sender didSendIQ:(XMPPIQ *)iq
{
    NSLog(@"%@",iq.XMLString);
}

/**
 *  XMPP收到消息
 *
 *  @param sender  XMPPStream
 *  @param message XMPPMessage
 */
-(void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    NSString * bodyString = [[message elementForName:@"body"] stringValue];
    NSData *myData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * result = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
    Message *tpMessage = [Message messageWithDic:result];
    if (tpMessage.messageType == MessageTypeForReceipt)
    {
        NSLog(@"收到回执");
        //为回执消息 -- 则需要处理这个回执消息 -- 更改DB数据，更改页面变化。
        ReceiptMessage *tpReceiptMessage = tpMessage.content;
        ReceiptAction tpReceiptAction = tpReceiptMessage.receiptAction;
        if (tpReceiptAction == JustReceive)
        {
            NSLog(@"消息达到");
        }
        else if (tpReceiptAction == WithChating)
        {
            NSLog(@"消息已读");
        }
    }
    else
    {
        //非回执消息，那么需要发送一条回执消息
        //构建回执消息
        NSLog(@"收到消息");
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *userName = [defaults objectForKey:XMPPUserName];
        
        Message *receiptMessage = [[Message alloc]init];
        receiptMessage.fromId = userName;
        receiptMessage.toId = tpMessage.fromId;
        receiptMessage.messageType = MessageTypeForReceipt;
        
        ReceiptMessage *tpReceiptMessage = [[ReceiptMessage alloc]init];
        tpReceiptMessage.message = tpMessage;
        tpReceiptMessage.receiptAction = JustReceive;
        receiptMessage.content = tpReceiptMessage;
        
        [self sendMessage:receiptMessage result:^(Message *message, MessageSendType sendType) {
            if (sendType == MessageIsSending)
            {
                NSLog(@"回执发送中");
            }
            else if (sendType == MessageSendSuccess)
            {
                NSLog(@"回执发送成功");
            }
            else
            {
                NSLog(@"回执发送失败");
            }
        }];
    }
    
}

/**
 *  收到好友在线状态
 *
 *  @param sender   XMPPStream
 *  @param presence 好友在线状态
 */
-(void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
{
    //获取用户在线状态
    NSString *presenceType = [presence type];
    
    //获取用户XMPP用户名
    NSString *presenceUserName = [[presence from] user];
    
    //获取当前登录用户XMPP用户名
    NSString *userName = [[sender myJID] user];
    
    if (![presenceUserName isEqualToString:userName] && presenceUserName != nil)
    {
        NSLog(@"收到好友：%@的在线状态",presenceUserName);
        //非当前登陆用户 -- 也就是收到好友的在线状态
        if ([presenceType isEqualToString:@"available"])
        {
            NSLog(@"好友在线");
        }
        else if ([presenceType isEqualToString:@"unavailable"])
        {
            NSLog(@"好友下线");
        }
        else if ([presenceType isEqualToString:@"subscribe"])
        {
            NSLog(@"对方同意添加好友");
        }
        else if ([presenceType isEqualToString:@"unsubscribe"])
        {
            NSLog(@"用户拒绝添加好友");
        }
    }
}

-(void)xmppStream:(XMPPStream *)sender didReceiveError:(DDXMLElement *)error
{
    
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark XMPPRosterDelegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/**
 *  开始获取好友列表
 *
 *  @param sender 好友列表
 */
-(void)xmppRosterDidBeginPopulating:(XMPPRoster *)sender
{
    
}

/**
 *  获取好友列表完成
 *
 *  @param sender 好友列表
 */
-(void)xmppRosterDidEndPopulating:(XMPPRoster *)sender
{
    NSLog(@"%@",sender.description);
}

/**
 *  获取到一个好友节点
 *
 *  @param sender 好友列表
 *  @param item   好友节点
 */
-(void)xmppRoster:(XMPPRoster *)sender didReceiveRosterItem:(DDXMLElement *)item
{
    NSLog(@"%@",item.description);
    
    NSString *ask = [item attributeStringValueForName:@"ask"];
    NSLog(@"%@",ask);
    
    NSString *name = [item attributeStringValueForName:@"name"];
    NSLog(@"%@",name);
    
    NSString *presenceFromUser =[item attributeStringValueForName:@"jid"];
    XMPPJID *jid = [XMPPJID jidWithString:presenceFromUser];
    NSString *subscription = [item attributeStringValueForName:@"subscription"];
    if ([subscription isEqualToString:@"both"])
    {
        NSLog(@"%@",jid.user);
        NSLog(@"双方已经互为好友");
    }
}

-(void)xmppRoster:(XMPPRoster *)sender didReceiveRosterPush:(XMPPIQ *)iq
{
    
}

/**
 *  收到好友请求
 *po
 *  @param sender   好友列表
 *  @param presence 好友请求
 */
-(void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence
{
    NSString *des = presence.description;
    NSLog(@"%@",des);
    //请求的用户
    NSString *presenceFromUser =[NSString stringWithFormat:@"%@",presence.from.user];
    NSLog(@"收到%@添加好友的请求",presenceFromUser);
    
    
    
//    XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",presenceFromUser,XMPPServerName]];
//    //接收添加好友请求
//    [xmppRoster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES];
}




/**
 *  聊天室创建成功
 *
 *  @param sender XMPPRoom
 */
-(void)xmppRoomDidCreate:(XMPPRoom *)sender
{
    
}

/**
 *  加入聊天室
 *
 *  @param sender XMPPRoom
 */
-(void)xmppRoomDidJoin:(XMPPRoom *)sender
{
    [xmppRoom fetchMembersList];
    [xmppRoom fetchModeratorsList];
}

/**
 *  获取到聊天室用户列表
 *
 *  @param sender XMPPRoom
 *  @param items  聊天室用户列表
 */
-(void)xmppRoom:(XMPPRoom *)sender didFetchMembersList:(NSArray *)items
{
    
}

/**
 *  没有获取到聊天室用户列表
 *
 *  @param sender  XMPPRoom
 *  @param iqError 聊天室用户列表
 */
-(void)xmppRoom:(XMPPRoom *)sender didNotFetchMembersList:(XMPPIQ *)iqError
{
    
}

/**
 *  获取到聊天室管理员列表
 *
 *  @param sender XMPPRoom
 *  @param items  管理员列表
 */
-(void)xmppRoom:(XMPPRoom *)sender didFetchModeratorsList:(NSArray *)items
{
    
}

/**
 *  没有获取到聊天室管理员列表
 *
 *  @param sender  XMPPRoom
 *  @param iqError 管理员列表
 */
-(void)xmppRoom:(XMPPRoom *)sender didNotFetchModeratorsList:(XMPPIQ *)iqError
{
    
}

/**
 *  收到聊天室消息
 *
 *  @param sender      XMPPRoom
 *  @param message     聊天室消息
 *  @param occupantJID 发言用户
 */
-(void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromOccupant:(XMPPJID *)occupantJID
{
    
}

/**
 *  新用户加入聊天室
 *
 *  @param sender      XMPPRoom
 *  @param occupantJID 加入用户名
 *  @param presence    用户状态
 */
-(void)xmppRoom:(XMPPRoom *)sender occupantDidJoin:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
{
    
}

/**
 *  用户离开聊天室
 *
 *  @param sender      XMPPRoom
 *  @param occupantJID 来开用户名
 *  @param presence    用户状态
 */
-(void)xmppRoom:(XMPPRoom *)sender occupantDidLeave:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
{
    
}

/**
 *  聊天室用户状态跟新
 *
 *  @param sender      XMPPRoom
 *  @param occupantJID 用户名
 *  @param presence    状态
 */
-(void)xmppRoom:(XMPPRoom *)sender occupantDidUpdate:(XMPPJID *)occupantJID withPresence:(XMPPPresence *)presence
{
    
}

/**
 *  离开聊天室
 *
 *  @param sender XMPPRoom
 */
-(void)xmppRoomDidLeave:(XMPPRoom *)sender
{
    
}

/**
 *  聊天室解散
 *
 *  @param sender XMPPRoom
 */
-(void)xmppRoomDidDestroy:(XMPPRoom *)sender
{
    
}

@end
